﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Best.SmartCms.Utility
{
    /// <summary>
    /// 时间帮助
    /// </summary>
    public static class TimeHelper
    {
        /// <summary>
        /// 获取某时刻的到当天结束的时间差
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static TimeSpan GetDayEndTimeSpan(DateTime time)
        {
            DateTime dt1 = DateTime.Parse(time.ToShortDateString() + " 23:59:59");
            DateTime dt2 = time;
            var ts = dt1 - dt2;
            return ts;
        }

        /// <summary>
        /// 创建时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string CreateTimestamp(DateTime time)
        {
            //Console.WriteLine("dt:{0}", time);
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t.ToString();
        }

        /// <summary>
        /// 时间戳转时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime TimestampToDateTime(string timeStamp)
        {
            var dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// 创建时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string ToyyyyMMddHHmmss(this DateTime? time)
        {
            return time == null ? "" : time.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 获取过期时间
        /// </summary>
        /// <param name="expireInSeconds">有效时间（秒）</param>
        /// <returns></returns>
        public static DateTime GetExpireTime(int expireInSeconds)
        {
            if (expireInSeconds > 3600)
            {
                expireInSeconds -= 600;//提前10分钟过期
            }
            else if (expireInSeconds > 1800)
            {
                expireInSeconds -= 300;//提前5分钟过期
            }
            else if (expireInSeconds > 300)
            {
                expireInSeconds -= 30;//提前1分钟过期
            }

            return DateTime.Now.AddSeconds(expireInSeconds);//提前2分钟重新获取
        }
    }
}
